package com.example.xf;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.fragment.AnalysisMainFragment;
import com.emm.yixun.mobile.fragment.AnalysisOptimizationFragment;
import com.emm.yixun.mobile.fragment.CustomerFragment;
import com.emm.yixun.mobile.fragment.HousingResourcesFragment;
import com.emm.yixun.mobile.fragment.MainFragment;
import com.emm.yixun.mobile.fragment.MyDataFragment;
import com.emm.yixun.mobile.model.GetMerchantResource;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetVersion;
import com.eroad.product.tools.DoubleClickExitApp;
import com.eroad.product.tools.PopuContent;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import xf.tointinataface.FlyprintInataface;
import xf.tointinataface.FlyprintInataface.onLoginClick;
import xf.tools.Loading;

//import com.emm.yixun.mobile.download.DownLoad;

/**
 * <p>
 * <customerFragment>Title：</customerFragment> 首页
 * </p>
 * <p>
 * <customerFragment>Description：</customerFragment> 下面有子布局: 首页 、客户 、 分析模块、我的、房源
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午3:17:17
 */
public class MainActivity extends BaseActivity implements onLoginClick {

    private static final String TAG = "-MainActivity-";

    /**
     * 父容器
     */
    FragmentManager manager;

    /**
     * 首页
     */
    MainFragment mainFragment = null;
    /**
     * 客户
     */
    CustomerFragment customerFragment = null;
    /**
     * 分析模块
     */
    AnalysisMainFragment analysisFragment = null;
    /**
     * 分析模块 优化版
     */
    AnalysisOptimizationFragment analysisOptimization = null;
    /**
     * 我的
     */
    MyDataFragment myDataFragment = null;
    /**
     * 房源
     */
    HousingResourcesFragment housingResourcesFragment = null;
    /**
     * 首页
     */
    ImageView btMain;
    /**
     * 客户
     */
    ImageView btCustomer;
    /**
     * 分析
     */
    ImageView btAnalysis;

    /**
     * 我的
     */
    ImageView btMyData;

    /**
     * 房源
     */
    ImageView btHousing;

    /**
     * back监听事件
     */
    DoubleClickExitApp mDoubleClickExitApp;

    /**
     * 线以及各模块文字view
     */
    TextView lines_v, btn_2_text, btn_3_text, btn_4_text, btn_5_text, btn_1_text;

    /**
     * 选中的首页模块
     */
    private int seleceType = 0;

    /**
     * 标题
     */
    TextView title_main, lines_top;

    /**
     * 向下的三角箭头
     */
    ImageView right_icon;

    /**
     * 商家图标（绿城东方）
     */
    ImageView left_icon;

    /**
     * 选中的项目
     */
    private int SelectPostion = 0;

    /**
     * 项目列表数据源
     */
    GetProjectList GetProject;

    View viewProject, view_p;
    /**
     * 项目选择弹出框
     */
    PopupWindow poPuProject;

    /**
     * 更多按钮
     */
    ImageView more_btn, ivMore;

    /**
     * 菜单
     */
    PopupWindow morePoPu;

    /**
     * 菜单
     */
    View view;

    /**
     * 取消群发
     */
    public Button cancel_btn;

    /**
     * 确定群发
     */
    public Button sure_btn;

    /**
     * 顶部布局父容器
     */
    RelativeLayout bgTopRelayout;

    /**
     * 首页
     */
    LinearLayout lvMain;

    /**
     * 客户
     */
    LinearLayout lvCustomer;

    /**
     * 房源
     */
    LinearLayout lvHousing;

    /**
     * 分析
     */
    LinearLayout lvAnalysis;

    /**
     * 我的
     */
    LinearLayout lvMyData;

    /**
     * 展开切换项目的点击区域
     */
    TextView btDrop;

    /**
     * 批量菜单
     */
    LinearLayout lvBatch;

    /**
     * 选择条数
     */
    TextView tvSelectSize;

    /**
     * 全选图标
     */
    ImageView ivSelectAll;

    /**
     * 是否全选
     */
    boolean isSelect = false;

    private int moveSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        JPushInterface.init(this);// 初始化极光
        JPushInterface.setDebugMode(true);// 开启debug模式
        fragmentall();// 实例化 父容器

        initview();

        SetViewHeight(bgTopRelayout);

        initBtn();
        EmmApplication.getCache();// 执行本地缓存的监测及清理

        if ("1".equals(EmmApplication.getData(EmmApplication.isHomePage))) {// 权限判断，用于设置第一次进入的默认界面
            select(1);
        } else {
            if ("1".equals(EmmApplication.getData(EmmApplication.isCustomer))) {
                select(2);
            } else {
                if ("1".equals(EmmApplication.getData(EmmApplication.isHouses))) {
                    select(5);
                } else {
                    if ("1".equals(EmmApplication.getData(EmmApplication.isAnalysis))) {
                        select(3);
                    } else {
                        if ("1".equals(EmmApplication.getData(EmmApplication.isMine))) {
                            select(4);
                        } else {
                            Log.v(TAG, "当前一个权限都没有");
                            right_icon.setVisibility(View.GONE);
                        }
                    }
                }
            }
        }

        // 注册back监听事件
        mDoubleClickExitApp = new DoubleClickExitApp(this);
        Loading.showDialogForLoading(MainActivity.this, "正在加载...", false, true, 60000);
        getProjectList();// 获取首页项目列表
        getVersion();// 版本信息获取

    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseActivity.activity = this;

        Log.v(TAG, "getRegistrationID:" + JPushInterface.getRegistrationID(MainActivity.this));

        if (EmmApplication.IsReloadProject) {
            Log.v(TAG, "刷新项目列表");
            EmmApplication.IsReloadProject = false;
            PopuContent.poPu(BaseActivity.activity, "存在项目组发生变更，请更新数据", false, 33);
            // Loading.showDialogForLoading(MainActivity.this, "正在加载...", false,
            // true, 60000);
            // getProjectList();
        }

        // 注册广播接收器
        IntentFilter filterr = new IntentFilter(EmmApplication.MAIN_ON_RESUME_TOBE);
        registerReceiver(mBroadcastReceiver, filterr);
        IntentFilter filter = new IntentFilter(EmmApplication.logout);
        registerReceiver(mBroadcastReceiver, filter);
        IntentFilter filter2 = new IntentFilter(EmmApplication.newdown);
        registerReceiver(mBroadcastReceiver, filter2);
        System.out.println("EmmApplication.IS_RELOAD:" + EmmApplication.IS_RELOAD);
        if (EmmApplication.IS_RELOAD) {// 客户列表是否刷新
            EmmApplication.IsReloadMain = true;// 首页刷新
            EmmApplication.IS_RELOAD = false;
            try {
                customerFragment.Reload();// 客户列表刷新方法
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        if (EmmApplication.IsReloadMain) {// 首页是否刷新
            EmmApplication.IsReloadMain = false;
            try {
                mainFragment.Reload();// 首页刷新方法
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        MobclickAgent.onResume(activity);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(activity);
    }

    /**
     * 广播监听方法
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (EmmApplication.logout.equals(action)) {// 从设置界面退出去之后，需要关闭首页，避免重新登录重复打开首页
                finish();
            }
            if (EmmApplication.newdown.equals(action)) {// 更新版本，下载进度监听
                Log.v(TAG, "下载------->");
                int downNum = intent.getIntExtra("downNum", 0);
                int length = intent.getIntExtra("length", 0);
                Log.v(TAG, "进度------->downNum:" + downNum + "--------/--------->length:" + length);

                if (null != tv_progress_view)
                    tv_progress_view.setText("已下载了" + downNum * 100 / length + "%");
                if (null != progressbar_view)
                    progressbar_view.setProgress(downNum * 100 / length);

                if (downNum >= length) {
                    EmmApplication.setLog(activity);
                    EmmApplication.Ts("下载完成~");
                    if (null != popu_call)
                        popu_call.dismiss();
                }
            }
            if (EmmApplication.MAIN_ON_RESUME_TOBE.equals(action)) {
                Reloadtobe();
            }
        }
    };

    /**
     * <p>
     * <customerFragment>Title：</customerFragment> 各类模块的刷新
     * </p>
     * <p>
     * <customerFragment>Description：</customerFragment>
     * </p>
     *
     * @author tangxin
     * @date 2017年2月23日 下午2:19:15
     */
    private void Reloadtobe() {
        title_main.setText(EmmApplication.getData(EmmApplication.ProjectName_content));
        if (seleceType == 1) {
            mainFragment.Reload();
        } else if (seleceType == 2) {
            customerFragment.Reload();
        } else if (seleceType == 3) {
            analysisFragment.Reload();
        } else if (seleceType == 4) {
            myDataFragment.Reload();
        } else if (seleceType == 5) {
            housingResourcesFragment.Reload();
        } else if (seleceType == 6) {
            analysisOptimization.DefaultGetTimeConditionAnalysis();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // /注销广播
        unregisterReceiver(mBroadcastReceiver);
        if (popu_call != null) {
            popu_call.dismiss();
        }
        super.onDestroy();
    }

    /**
     * <p>
     * <customerFragment>Title：</customerFragment> 初始化view
     * </p>
     * <p>
     * <customerFragment>Description：</customerFragment> 将xml控件与声明的view根据ID绑定
     * </p>
     *
     * @author tangxin
     * @date 2016年12月6日 下午3:24:56
     */
    private void initview() {
        ivMore = (ImageView) findViewById(R.id.back_btn);
        btMain = (ImageView) findViewById(R.id.btn1);// 首页
        btCustomer = (ImageView) findViewById(R.id.btn2);// 客户
        btAnalysis = (ImageView) findViewById(R.id.btn3);// 分析
        btMyData = (ImageView) findViewById(R.id.btn4);// 我的
        btHousing = (ImageView) findViewById(R.id.btne);// 房源
        lines_v = (TextView) findViewById(R.id.lines_v);
        btn_1_text = (TextView) findViewById(R.id.btn_1_text);// 首页
        btn_2_text = (TextView) findViewById(R.id.btn_2_text);// 客户
        btn_3_text = (TextView) findViewById(R.id.btn_3_text);// 房源
        btn_4_text = (TextView) findViewById(R.id.btn_4_text);// 分析
        btn_5_text = (TextView) findViewById(R.id.btn_5_text);// 我的
        bgTopRelayout = (RelativeLayout) findViewById(R.id.bg_top_rela);
        lvCustomer = (LinearLayout) findViewById(R.id.btn2_q);// 客户
        view_p = findViewById(R.id.mainactivity_include);
        lvMain = (LinearLayout) findViewById(R.id.btn1_q);// 首页
        lvHousing = (LinearLayout) findViewById(R.id.btne_q);// 房源
        lvAnalysis = (LinearLayout) findViewById(R.id.btn3_q);// 分析
        lvMyData = (LinearLayout) findViewById(R.id.btn4_q);// 我的
        more_btn = (ImageView) view_p.findViewById(R.id.more_btn);// 更多
        cancel_btn = (Button) view_p.findViewById(R.id.cancel_btn);// 取消
        sure_btn = (Button) view_p.findViewById(R.id.sure_btn);// 确定
        title_main = (TextView) findViewById(R.id.title_main);// 标题
        left_icon = (ImageView) findViewById(R.id.left_icon);// 绿城东方
        left_icon.setVisibility(View.VISIBLE);
        lines_top = (TextView) findViewById(R.id.lines_top);
        right_icon = (ImageView) findViewById(R.id.right_icon);// 向下三角
        right_icon.setVisibility(View.VISIBLE);
        lines_1 = (TextView) findViewById(R.id.lines_1);
        lines_2 = (TextView) findViewById(R.id.lines_2);
        lines_4 = (TextView) findViewById(R.id.lines_4);
        btDrop = (TextView) findViewById(R.id.drop_btn);
        lvBatch = (LinearLayout) findViewById(R.id.batch_linear);
        ivSelectAll = (ImageView) findViewById(R.id.select_all_image);
        tvSelectSize = (TextView) findViewById(R.id.select_size);

        // 配置 options 参数方法
        EmmApplication.image(R.drawable.ic_richpush_actionbar_divider);
        // 图像展示
        EmmApplication.imageLoader.displayImage(EmmApplication.getData(EmmApplication.FistSrcPatch), left_icon,
                EmmApplication.options);

    }

    /**
     * 底部模块的分界线,根据当前模块是否存在，而显示或者隐藏
     */
    TextView lines_1, lines_2, lines_4;

    /**
     * <p>
     * <customerFragment>Title：</customerFragment> 初始化监听事件
     * </p>
     * <p>
     * <customerFragment>Description：</customerFragment> 初始化按钮的点击监听，判断显示等
     * </p>
     *
     * @author tangxin
     * @date 2016年12月6日 下午3:25:39
     */
    private void initBtn() {

        // 菜单权限：首页 String(1) 首页：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isHomePage))) {
            lvMain.setVisibility(View.VISIBLE);
            lines_1.setVisibility(View.VISIBLE);
        } else {
            lvMain.setVisibility(View.GONE);
            lines_1.setVisibility(View.GONE);
        }

        // 菜单权限：客户 String(1) 客户：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isCustomer))) {
            lvCustomer.setVisibility(View.VISIBLE);
            lines_2.setVisibility(View.VISIBLE);
        } else {
            lvCustomer.setVisibility(View.GONE);
            lines_2.setVisibility(View.GONE);
        }

        // 菜单权限：房源 String(1) 房源：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isHouses))) {
            lvHousing.setVisibility(View.VISIBLE);
            lines_v.setVisibility(View.VISIBLE);
        } else {
            lvHousing.setVisibility(View.GONE);
            lines_v.setVisibility(View.GONE);
        }

        // 菜单权限：分析 String(1) 分析：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isAnalysis))) {
            lvAnalysis.setVisibility(View.VISIBLE);
            lines_4.setVisibility(View.VISIBLE);
        } else {
            lvAnalysis.setVisibility(View.GONE);
            lines_4.setVisibility(View.GONE);
        }

        // 菜单权限：我的 String(1) 我的：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isMine))) {
            lvMyData.setVisibility(View.VISIBLE);

            // 菜单权限：分析 String(1) 分析：0 无 1 有
            if ("1".equals(EmmApplication.getData(EmmApplication.isAnalysis))) {
                lines_4.setVisibility(View.VISIBLE);
            } else {
                lines_4.setVisibility(View.GONE);
            }
        } else {
            lvMyData.setVisibility(View.GONE);
            lines_4.setVisibility(View.GONE);
        }

        // 初始化菜单PopupWindow 客户碎片有更多菜单
        InitPopuWindow();
        more_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleceType == 5) {
                    housingResourcesFragment.OpenBigJpg();// 打开总平图
                } else if (seleceType == 2) {
                    customerFragment.newcustomerset();
                } else if (seleceType == 6) {// 分析的分享
                    analysisOptimization.ShareBitmap();
                }
            }
        });

        ivMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出框（搜索，群发短信，新增用户）
                // morePopu存在就dismiss,不存在就show
                if (morePoPu.isShowing())
                    morePoPu.dismiss();
                else
                    morePoPu.showAsDropDown(more_btn, 0, 0);
            }
        });

        // 点击标题，打开项目切换列表
        title_main.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != GetProject && null != GetProject.getProjectList()) {
                    SetsortPopu(GetProject);// 项目切换列表
                }
            }
        });

        // 展开切换项目的点击区域
        btDrop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != GetProject && null != GetProject.getProjectList()) {
                    SetsortPopu(GetProject);
                }
            }
        });

        // 向下的三角箭头
        right_icon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (GetProject.getProjectList() != null) {
                        SetsortPopu(GetProject);
                    }
                } catch (NullPointerException e) {
                    Log.v(TAG, "MainActivity is null");
                }
            }
        });

        // 取消群发
        cancel_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                customerFragment.disselect();
                gone();
                ivMore.setVisibility(View.VISIBLE);
                more_btn.setVisibility(View.VISIBLE);
                isSelect = false;
                SetVisibleView(isSelect);
                if (customerFragment != null)
                    customerFragment.select_bl = true;
            }
        });

        // 确认群发
        sure_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                customerFragment.shure();// 发起短信或批量分配方法
                gone();
                ivMore.setVisibility(View.VISIBLE);
                more_btn.setVisibility(View.VISIBLE);
                isSelect = false;
                SetVisibleView(isSelect);
                if (customerFragment != null)
                    customerFragment.select_bl = true;
            }
        });

        // 房源
        lvHousing.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleceType == 5) {
                    return;
                }
                select(5);// 选择模块
                ivMore.setVisibility(View.GONE);
                housingResourcesFragment.Reload();// 刷新
                more_btn.setVisibility(View.VISIBLE);
                more_btn.setImageResource(R.drawable.ioc_pic);
                if ((null != customerFragment && !customerFragment.select_bl) || isSelect) {// 根据批量状态隐藏相关view
                    gone();
                }
            }
        });

        // 首页
        lvMain.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleceType == 1) {
                    return;
                }
                select(1);
                ivMore.setVisibility(View.GONE);
                more_btn.setVisibility(View.GONE);
                if ((null != customerFragment && !customerFragment.select_bl) || isSelect) {// 根据批量状态隐藏相关view
                    gone();
                }
            }
        });

        // 客户
        lvCustomer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleceType == 2) {
                    return;
                }
                select(2);
                if ("1".equals(EmmApplication.getData(EmmApplication.isAddCustomer))) {
                    more_btn.setVisibility(View.VISIBLE);
                    more_btn.setImageResource(R.drawable.ic_add_customer);
                }
                ivMore.setVisibility(View.VISIBLE);
                ivMore.setImageResource(R.drawable.ioc_3);
                if ((null != customerFragment && !customerFragment.select_bl) || isSelect) {// 根据群发状态隐藏相关view
                    cancel_btn.setVisibility(View.VISIBLE);
                    sure_btn.setVisibility(View.VISIBLE);
                    more_btn.setVisibility(View.GONE);
                    lvBatch.setVisibility(View.VISIBLE);
                }
            }
        });

        // 分析
        lvAnalysis.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleceType == 6) {
                    return;
                }
                select(6);
                ivMore.setVisibility(View.GONE);
                more_btn.setVisibility(View.VISIBLE);
                more_btn.setImageResource(R.drawable.ico_share);
                if ((null != customerFragment && !customerFragment.select_bl) || isSelect) {// 根据批量状态隐藏相关view
                    gone();
                }
            }
        });

        // 我的
        lvMyData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleceType == 4) {
                    return;
                }
                select(4);
                ivMore.setVisibility(View.GONE);
                more_btn.setVisibility(View.GONE);
                if ((null != customerFragment && !customerFragment.select_bl) || isSelect) {// 根据批量状态隐藏相关view
                    gone();
                }
            }
        });

        // 全选
        ivSelectAll.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelect) {
                    isSelect = false;
                    ivSelectAll.setImageResource(R.drawable.ico_delt_no);
                } else {
                    isSelect = true;
                    ivSelectAll.setImageResource(R.drawable.ico_selt);
                }
                customerFragment.SelectOrCancelAll(isSelect);
            }
        });
    }

    /**
     * <p>
     * <customerFragment>Title：</customerFragment> 实例化 父容器
     * </p>
     * <p>
     * <customerFragment>Description：</customerFragment> 父类为activity则用getSupportFragmentManager，否则需要得到的是子管理器
     * </p>
     *
     * @author tangxin
     * @date 2016年12月6日 下午3:26:29
     */
    private void fragmentall() {
        manager = getSupportFragmentManager();
        FlyprintInataface.setmLoginClick(this);
    }

    FragmentTransaction transaction;

    /**
     * <p>
     * <customerFragment>Title：</customerFragment> 选择模块
     * </p>
     * <p>
     * <customerFragment>Description：</customerFragment> 根据选择的模块处理展示当前选中的fragment
     * </p>
     *
     * @param num 选中的哪一个
     * @author tangxin
     * @date 2016年12月6日 下午3:27:13
     */
    public void select(int num) {
        transaction = manager.beginTransaction();
        seleceType = num;
        // 判断是否已创建，已创建的就做隐藏
        if (mainFragment != null) {
            transaction.hide(mainFragment);
        }
        if (customerFragment != null) {
            transaction.hide(customerFragment);
        }
        if (analysisFragment != null) {
            transaction.hide(analysisFragment);
        }
        if (myDataFragment != null) {
            transaction.hide(myDataFragment);
        }
        if (housingResourcesFragment != null) {
            transaction.hide(housingResourcesFragment);
        }
        if (analysisOptimization != null) {
            transaction.hide(analysisOptimization);
        }
        setbgcolor(num);// 对应模块按钮的颜色的修改
        switch (num) {
            case 1:
                bgTopRelayout.setBackgroundResource(R.drawable.shape_title_bar);// 设置顶部标题渐变色
                title_main.setTextColor(Color.parseColor("#ffffff"));
                right_icon.setVisibility(View.VISIBLE);
                left_icon.setVisibility(View.VISIBLE);
                lines_top.setVisibility(View.VISIBLE);
                right_icon.setImageResource(R.drawable.right_icon);
                seleceType = 1;
                if (mainFragment == null) {
                    mainFragment = new MainFragment();
                    transaction.add(R.id.mainactivity_fragmrnt, mainFragment);
                } else {
                    transaction.show(mainFragment);
                }
                break;
            case 2:
                bgTopRelayout.setBackgroundResource(R.drawable.shape_title_bar2);
                title_main.setTextColor(Color.parseColor("#262626"));
                left_icon.setVisibility(View.GONE);
                lines_top.setVisibility(View.GONE);
                right_icon.setImageResource(R.drawable.sj_down);
                seleceType = 2;
                if (customerFragment == null) {
                    customerFragment = new CustomerFragment();
                    transaction.add(R.id.mainactivity_fragmrnt, customerFragment);
                } else {
                    transaction.show(customerFragment);
                }
                break;
            case 3:
                bgTopRelayout.setBackgroundResource(R.drawable.shape_title_bar2);
                title_main.setTextColor(Color.parseColor("#262626"));
                left_icon.setVisibility(View.GONE);
                lines_top.setVisibility(View.GONE);
                right_icon.setImageResource(R.drawable.sj_down);
                seleceType = 3;
                if (analysisFragment == null) {
                    analysisFragment = new AnalysisMainFragment();
                    transaction.add(R.id.mainactivity_fragmrnt, analysisFragment);
                } else {
                    transaction.show(analysisFragment);
                }
                break;
            case 4:
                // bgTopRelayout.setBackgroundColor(Color.parseColor("#20ffffff"));
                setBackgroundColor(moveSize);
                right_icon.setVisibility(View.VISIBLE);
                left_icon.setVisibility(View.GONE);
                lines_top.setVisibility(View.GONE);
                seleceType = 4;
                if (myDataFragment == null) {
                    myDataFragment = new MyDataFragment();
                    transaction.add(R.id.mainactivity_fragmrnt, myDataFragment);
                } else {
                    transaction.show(myDataFragment);
                }
                break;
            case 5:
                bgTopRelayout.setBackgroundResource(R.drawable.shape_title_bar2);
                title_main.setTextColor(Color.parseColor("#262626"));
                right_icon.setImageResource(R.drawable.sj_down);
                left_icon.setVisibility(View.GONE);
                lines_top.setVisibility(View.GONE);
                seleceType = 5;
                if (housingResourcesFragment == null) {
                    housingResourcesFragment = new HousingResourcesFragment();
                    transaction.add(R.id.mainactivity_fragmrnt, housingResourcesFragment);
                } else {
                    transaction.show(housingResourcesFragment);
                }
                break;
            case 6:
                bgTopRelayout.setBackgroundResource(R.drawable.shape_title_bar2);
                title_main.setTextColor(Color.parseColor("#262626"));
                left_icon.setVisibility(View.GONE);
                lines_top.setVisibility(View.GONE);
                right_icon.setImageResource(R.drawable.sj_down);
                seleceType = 6;
                if (analysisOptimization == null) {
                    analysisOptimization = new AnalysisOptimizationFragment();
                    transaction.add(R.id.mainactivity_fragmrnt, analysisOptimization);
                } else {
                    transaction.show(analysisOptimization);
                }
                break;
        }
        transaction.commit();// 对本次操作做提交
    }

    @Override
    public void onLogin(int num) {// 接口回调
        select(num);
    }

    /**
     * 隐藏布局
     */
    public void gone() {
        Log.v(TAG, " gone()");
        try {
            cancel_btn.setVisibility(View.GONE);
            sure_btn.setVisibility(View.GONE);
            lvBatch.setVisibility(View.GONE);
        } catch (NullPointerException e) {
        }
    }

    /**
     * 在处理onKeyDown事件中调用Back工具类方法即可
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return mDoubleClickExitApp.onKeyDown(keyCode, event);
        } else {
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 选中颜色更改
     */
    private void setbgcolor(int i) {
        if (6 == i) {
            i = 3;
        }
        btMain.setImageResource(i == 1 ? R.drawable.btn_1a : R.drawable.btn_1);
        btn_1_text.setTextColor(i == 1 ? Color.parseColor("#FF7F18") : Color.parseColor("#9A9A9A"));
        btCustomer.setImageResource(i == 2 ? R.drawable.btn_2a : R.drawable.btn_2);
        btn_2_text.setTextColor(i == 2 ? Color.parseColor("#FF7F18") : Color.parseColor("#9A9A9A"));
        btAnalysis.setImageResource(i == 3 ? R.drawable.btn_4a : R.drawable.btn_4);
        btn_4_text.setTextColor(i == 3 ? Color.parseColor("#FF7F18") : Color.parseColor("#9A9A9A"));
        btMyData.setImageResource(i == 4 ? R.drawable.btn_5a : R.drawable.btn_5);
        btn_5_text.setTextColor(i == 4 ? Color.parseColor("#FF7F18") : Color.parseColor("#9A9A9A"));
        btHousing.setImageResource(i == 5 ? R.drawable.btn_3a : R.drawable.btn_3);
        btn_3_text.setTextColor(i == 5 ? Color.parseColor("#FF7F18") : Color.parseColor("#9A9A9A"));
    }

    /**
     * 首页项目列表接口
     */
    private void getProjectList() {
        EmmApplication.updateUrl("getProjectList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getProjectList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, "content:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = null;
                try {
                    resData = (JSONObject) jsonObj.get("resData");
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                GetProject = JSONObject.parseObject(resData.toString(), GetProjectList.class);

                if ("1".equals(GetProject.getResult())) {
                    EmmApplication.ErrorCode = "10010";
                    Log.v("获取成功", "");
                    if (GetProject.getProjectList() != null && GetProject.getProjectList().size() >= 1) {
                        EmmApplication.setData(EmmApplication.PROJECT_LIST_ISNULL, "0");
                        title_main.setText(GetProject.getProjectList().get(0).getProjectName());// 设置首页项目标题
                        // 默认选中第一个项目
                        EmmApplication.setData(EmmApplication.ProjectName_content, GetProject.getProjectList().get(0)
                                .getProjectName());
                        EmmApplication.setProjectCode(GetProject.getProjectList().get(0).getProjectCode());
                        EmmApplication.setProjectID(GetProject.getProjectList().get(0).getProjectId());
                        if ("1".equals(EmmApplication.getData(EmmApplication.isHomePage)))
                            mainFragment.Reload();
                        getMerchantResource();
                    } else {
                        EmmApplication.T("项目列表为空");
                        EmmApplication.setData(EmmApplication.PROJECT_LIST_ISNULL, "1");
                        if ("1".equals(EmmApplication.getData(EmmApplication.isHomePage)))
                            mainFragment.Reload();
                    }

                } else {
                    // errorCode:31010errorMsg:该用户暂无项目数据权限，请联系管理员
                    EmmApplication.T(GetProject.getErrorMsg().toString());
                    EmmApplication.ErrorCode = GetProject.getErrorCode().toString();
                    Log.v("EmmApplication.ErrorCode", "EmmApplication.ErrorCode:" + EmmApplication.ErrorCode);
                    Log.v("获取失败", "errorCode:" + GetProject.getErrorCode().toString() + "errorMsg:"
                            + GetProject.getErrorMsg().toString());
                }
            }
        });
    }

    /**
     * 项目切换
     */
    public void SetsortPopu(final GetProjectList list) {
        viewProject = LayoutInflater.from(MainActivity.this).inflate(R.layout.mainproject_popu, null);
        poPuProject = new PopupWindow(viewProject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        poPuProject.setFocusable(true);
        poPuProject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        poPuProject.showAtLocation(view_p, Gravity.TOP, 0, 0);
        poPuProject.showAsDropDown(view_p, 0, 0);
        poPuProject.setFocusable(true);
        poPuProject.setOutsideTouchable(true);
        viewProject.setFocusable(true);
        viewProject.setFocusableInTouchMode(true);
        viewProject.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    poPuProject.dismiss();
                    EmmApplication.setLog(MainActivity.this);
                }
                return false;
            }
        });
        viewProject.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuProject.dismiss();
                EmmApplication.setLog(MainActivity.this);
            }
        });
        ListView popu_list = (ListView) viewProject.findViewById(R.id.popu_list);
        RelativeLayout top_relativelayout = (RelativeLayout) viewProject.findViewById(R.id.top_relativelayout);
        SetViewPaddingHeight(top_relativelayout, 50);

        MainProjectAdapter adapter = new MainProjectAdapter(MainActivity.this, list);
        popu_list.setAdapter(adapter);// 绑定adapter，展示数据
        if (null == list) {
        } else {// 默认选中一个
            adapter.SeleCt(SelectPostion);
            popu_list.setSelection(SelectPostion);
        }
        title_main.setText(list.getProjectList().get(SelectPostion).getProjectName());// 显示默认选中的
        popu_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SelectPostion = position;
                Log.v(TAG, "点击了" + list.getProjectList().get(position).getProjectName());

                poPuProject.dismiss();// 隐藏popupwindow

                EmmApplication.setLog(MainActivity.this);// 恢复屏幕亮度

                title_main.setText(list.getProjectList().get(position).getProjectName());

                // 获取当前项目选择是否变更,变更了就更新
                if (EmmApplication.getProjectID().equals(list.getProjectList().get(position).getProjectId())) {
                    EmmApplication.IS_RELOAD = false;
                    EmmApplication.IS_RELOAD_ANALYSIS = false;
                } else {

                    // 存储项目名
                    EmmApplication.setData(EmmApplication.ProjectName_content, list.getProjectList().get(position)
                            .getProjectName());

                    // 存储项目code
                    EmmApplication.setProjectCode(list.getProjectList().get(position).getProjectCode());

                    // 存储项目ID
                    EmmApplication.setProjectID(list.getProjectList().get(position).getProjectId());

                    Log.v(TAG, "客户列表、运营分析需要刷新");
                    EmmApplication.IS_RELOAD = true;
                    EmmApplication.IS_RELOAD_ANALYSIS = true;
                }

                // 切换项目之后，刷新当前选中的模块

                if (seleceType == 1)
                    mainFragment.Reload();
                else if (seleceType == 2) {
                    customerFragment.Reload();
                    gone();
                    more_btn.setVisibility(View.VISIBLE);
                } else if (seleceType == 3) {
                    analysisFragment.Reload();
                } else if (seleceType == 4) {
                    myDataFragment.Reload();
                } else if (seleceType == 5) {
                    housingResourcesFragment.Reload();
                } else if (seleceType == 6) {
                    analysisOptimization.DefaultGetTimeConditionAnalysis();
                }
                getMerchantResource();
            }
        });
    }

    /**
     * 初始化菜单PopupWindow 客户碎片有更多菜单
     */
    @SuppressWarnings("deprecation")
    public void InitPopuWindow() {
        view = LayoutInflater.from(MainActivity.this).inflate(R.layout.morep, null);
        morePoPu = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        // 设置焦点
        morePoPu.setFocusable(true);
        morePoPu.setOutsideTouchable(true);
        // view的焦点
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        // 监听back按钮
        view.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    morePoPu.dismiss();
                }
                return false;
            }
        });
        // 点击popupwindow范围外,popupwindow消失
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
            }
        });

        LinearLayout search = (LinearLayout) view.findViewById(R.id.search);// 搜索
        LinearLayout sms = (LinearLayout) view.findViewById(R.id.sms);// 短信
        LinearLayout addCoustomer = (LinearLayout) view.findViewById(R.id.add_coustomer);// 新增客户
        LinearLayout allot = (LinearLayout) view.findViewById(R.id.allot);// 批量分配
        LinearLayout add_form = (LinearLayout) view.findViewById(R.id.add_form);// 新增认筹
        LinearLayout add_phone = (LinearLayout) view.findViewById(R.id.add_phone);// 添加到通讯录

        View lines_4 = view.findViewById(R.id.lines_4);
        View lines_3s = view.findViewById(R.id.lines_3s);
        View lines_3 = view.findViewById(R.id.lines_3);
        View lines_2 = view.findViewById(R.id.lines_2);
        View line1 = view.findViewById(R.id.lines_1);

        search.setVisibility(View.GONE);
        addCoustomer.setVisibility(View.GONE);
        line1.setVisibility(View.GONE);
        lines_3.setVisibility(View.GONE);

        add_form.setVisibility(View.GONE);
        add_phone.setVisibility(View.GONE);
        lines_4.setVisibility(View.GONE);
        lines_3s.setVisibility(View.GONE);

        // 客户菜单权限下按钮权限：客户新增 String(1) 客户新增：0 无 1 有
//        if ("1".equals(EmmApplication.getData(EmmApplication.isAddCustomer))) {
//            addCoustomer.setVisibility(View.VISIBLE);
//            lines_2.setVisibility(View.VISIBLE);
//        } else {
//            addCoustomer.setVisibility(View.GONE);
//            lines_2.setVisibility(View.GONE);
//        }

        // 客户菜单权限下按钮权限：客户新增 String(1) 客户新增：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isDistributionCustomer))) {
            allot.setVisibility(View.VISIBLE);
            lines_3.setVisibility(View.VISIBLE);
        } else {
            allot.setVisibility(View.GONE);
            lines_3.setVisibility(View.GONE);
        }

        // 搜索
        search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
                customerFragment.searchset();
            }
        });

        // 新增
        addCoustomer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
                customerFragment.newcustomerset();
            }
        });

        // 群发短信
        sms.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
                customerFragment.smsset();
                cancel_btn.setVisibility(View.VISIBLE);
                sure_btn.setVisibility(View.VISIBLE);
                more_btn.setVisibility(View.GONE);
                ivMore.setVisibility(View.GONE);
                lvBatch.setVisibility(View.VISIBLE);
            }
        });

        // 批量指派
        allot.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
                customerFragment.allotset();
                cancel_btn.setVisibility(View.VISIBLE);
                sure_btn.setVisibility(View.VISIBLE);
                more_btn.setVisibility(View.GONE);
                ivMore.setVisibility(View.GONE);
                lvBatch.setVisibility(View.VISIBLE);
            }
        });
    }

    GetVersion getversion;

    /**
     * 版本信息
     */
    private void getVersion() {
        EmmApplication.updateUrl("getVersion");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("versionType", "1");
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getVersion-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "版本更新校验-->请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                getversion = JSONObject.parseObject(resData.toString(), GetVersion.class);

                if ("1".equals(getversion.getResult())) {
                    Log.v("获取成功", "");
                    // tips("1.0.2", "测试下载内容", true);
                    EmmApplication.DownLoadingUrl = getversion.getVersionUrlAddress();
                    if ("1".equals(getversion.getVersionStatus()) || "2".equals(getversion.getVersionStatus())) {// 可升级
                        handler.sendEmptyMessage(11);
                    } else {// 不可升级
                    }
                } else {
                    EmmApplication.Ts(getversion.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getversion.getErrorCode().toString() + "errorMsg:"
                            + getversion.getErrorMsg().toString());
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 11) {
                if ("1".equals(getversion.getVersionStatus())) {// 可升级
                    Log.v(TAG, "可升级");
                    popu("更新版本：" + getversion.getVersionName(), getversion.getVersionDes(), true,
                            EmmApplication.DownLoadingUrl);
                } else {// 强制升级
                    Log.v(TAG, "强制升级");
                    popu("更新版本：" + getversion.getVersionName(), getversion.getVersionDes(), false,
                            EmmApplication.DownLoadingUrl);
                }
            }
            if (msg.what == 202) {
                if (null != tv_progress_view) {
                    tv_progress_view.setText("已下载了" + mProgress * 100 / mLength + "%");
                }
                if (null != progressbar_view) {
                    progressbar_view.setProgress(mProgress * 100 / mLength);
                }
                if (mProgress >= mLength) {
                    EmmApplication.setLog(activity);
                    EmmApplication.Ts("下载完成~");
                    if (null != popu_call)
                        popu_call.dismiss();
                }
            }
        }
    };

    public View view3;
    public PopupWindow popu_call;

    TextView tv_progress_view;

    ProgressBar progressbar_view;

    int mProgress;
    int mLength;

    /**
     * msg 更新的版本号 content 内容 isVscancel是否强制升级
     */
    @SuppressLint("WrongConstant")
    public void popu(String msg, String content, final boolean isVscancel, final String DownLoadingUrl) {
        view3 = LayoutInflater.from(MainActivity.this).inflate(R.layout.popu_shuerdp_apk, null);
        popu_call = new PopupWindow(view3, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        popu_call.setFocusable(true);

        popu_call.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popu_call.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        popu_call.showAtLocation(view3, Gravity.CENTER, 0, 0);
        popu_call.showAsDropDown(view3, 0, 0);
        popu_call.setFocusable(true);
        popu_call.setOutsideTouchable(true);

        view3.setFocusable(isVscancel);
        view3.setFocusableInTouchMode(isVscancel);

        view3.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (isVscancel) {
                        popu_call.dismiss();
                        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        activity.getWindow().setAttributes(lp);
                    } else {
                    }
                }
                return false;
            }
        });

        TextView dismiss = (TextView) view3.findViewById(R.id.dismiss);// 取消
        TextView shuerbtn = (TextView) view3.findViewById(R.id.shuerbtn);// 确定
        TextView version_content = (TextView) view3.findViewById(R.id.version_content);// 版本介绍
        TextView getpakage_version = (TextView) view3.findViewById(R.id.getpakage_version);// 版本信息

        tv_progress_view = (TextView) view3.findViewById(R.id.tv_progress_view);
        progressbar_view = (ProgressBar) view3.findViewById(R.id.progressbar_view);
        progressbar_view.setMax(100);

        getpakage_version.setText("当前版本：" + EmmApplication.getPackageManager(9));
        final RelativeLayout vs_view = (RelativeLayout) view3.findViewById(R.id.vs_view);
        final LinearLayout gone_view = (LinearLayout) view3.findViewById(R.id.gone_view);
        TextView new_versin_name = (TextView) view3.findViewById(R.id.new_versin_name);
        new_versin_name.setText(msg);
        version_content.setText(content);

        if (isVscancel) {
            dismiss.setVisibility(View.VISIBLE);
        } else {
            dismiss.setVisibility(View.GONE);
        }
        dismiss.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EmmApplication.IsUpdate) {
                    popu_call.dismiss();
                    if (isVscancel) {
                        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        activity.getWindow().setAttributes(lp);
                    } else {
                        System.exit(0);
                    }
                } else {
                    EmmApplication.Ts("正在下载新版本...");
                }
            }
        });
        shuerbtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EmmApplication.IsUpdate) {
                    EmmApplication.IsUpdate = false;
                    DownloadInterface.init(new DownloadInterface.download() {
                        @Override
                        public void progress(int progress, int length) {
                            mProgress = progress;
                            mLength = length;
                            handler.sendEmptyMessage(202);
                        }
                    });
                    Intent updateIntent = new Intent(MainActivity.this, com.eroad.product.tools.UpdateAppService.class);
                    startService(updateIntent);

                    gone_view.setVisibility(View.GONE);
                    vs_view.setVisibility(View.VISIBLE);
                } else {
                    EmmApplication.Ts("下载正在进行~");
                }
            }
        });
        view3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVscancel) {
                    popu_call.dismiss();
                    WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                    lp.alpha = 1f;
                    activity.getWindow().setAttributes(lp);
                } else {
                }
            }
        });
    }

    /**
     * 通过接口实现传值并渲染界面 选择条数
     */
    @Override
    public void setSize(int size) {
        tvSelectSize.setText("已选" + size + "条");
    }

    /**
     * 通过接口实现传值并渲染界面 是否全选
     */
    @Override
    public void isSelect(boolean select) {
        isSelect = select;
        SetVisibleView(isSelect);

    }

    private void SetVisibleView(boolean select) {
        if (isSelect) {
            ivSelectAll.setImageResource(R.drawable.ico_selt);
        } else {
            ivSelectAll.setImageResource(R.drawable.ico_delt_no);
        }
    }

    @Override
    public void ReloadProjectList() {
        getProjectList();
    }

    @Override
    public void finishMain() {
        if (EmmApplication.getIsVisibleActivity(this, "com.example.xf.MainActivity")) {
            Log.v(TAG, "当前activity存在,关闭");
            finish();
        } else {
            Log.v(TAG, "当前activity不存在");
        }
    }

    @Override
    public void ReloadAllmode() {
        if (EmmApplication.getIsVisibleActivity(this, "com.example.xf.MainActivity")) {
            Log.v(TAG, "当前activity存在,刷新");
            Reloadtobe();
        } else {
            Log.v(TAG, "当前activity不存在,不刷新");
        }
    }

    @Override
    public void MoveSize(int size) {
        moveSize = size;
        setBackgroundColor(moveSize);
    }

    private void setBackgroundColor(int size) {
        if (size < 10) {
            size = 20;
        }
        if (size >= 255) {
            size = 255;
        }
        if (size < (255 / 2)) {
            title_main.setTextColor(Color.parseColor("#ffffff"));
            right_icon.setImageResource(R.drawable.right_icon);
        } else {
            title_main.setTextColor(Color.parseColor("#000000"));
            right_icon.setImageResource(R.drawable.sj_down);
        }
        bgTopRelayout.setBackgroundColor(Color.parseColor("#f8f8f8"));
        bgTopRelayout.getBackground().setAlpha(size);
    }

    private void getMerchantResource() {
        EmmApplication.updateUrl("getMerchantResource");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", EmmApplication.getProjectCode());
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getMerchantResource", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }
                GetMerchantResource getMerchantResource = JSONObject.parseObject(resData.toString(), GetMerchantResource.class);
                if ("1".equals(getMerchantResource.getResult())) {
                    EmmApplication.setTips(getMerchantResource.getNecessary());
                } else {
                    try {
                        EmmApplication.Ts(getMerchantResource.getErrorMsg());
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


}
